package com.acwing.partition21;

import java.io.*;
import java.util.*;

/**
 * @author `RKC`
 * @date 2022/1/4 20:09
 */
public class AC2060奶牛选美dfs {

    private static final int N = 51, M = 51;
    private static char[][] graph = new char[N][M];
    private static int n = 0, m = 0;
    private static final int[][] dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
    private static List<List<int[]>> pointList = new ArrayList<>(2);

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] s = reader.readLine().split("\\s+");
        n = Integer.parseInt(s[0]);
        m = Integer.parseInt(s[1]);
        for (int i = 0; i < n; i++) {
            String str = reader.readLine();
            for (int j = 0; j < m; j++) {
                graph[i][j] = str.charAt(j);
            }
        }
        for (int i = 0, k = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                //从每一个X开始出发，将这个连通区域里面的所有X都加入进来
                if (graph[i][j] == 'X') {
                    pointList.add(new ArrayList<>());
                    dfs(i, j, pointList.get(k++));
                }
            }
        }
        int answer = 0x3f3f3f3f;
        for (int[] point1 : pointList.get(0)) {
            for (int[] point2 : pointList.get(1)) {
                //计算任意两个连通点的曼哈顿距离，取最小
                answer = Math.min(answer, Math.abs(point1[0] - point2[0]) + Math.abs(point1[1] - point2[1]) - 1);
            }
        }
        writer.write(answer + "\n");
        writer.flush();
    }

    private static void dfs(int x, int y, List<int[]> points) {
        //将X变成.，并记录下来当前经过的点
        graph[x][y] = '.';
        points.add(new int[]{x, y});
        for (int[] dir : dirs) {
            int i = x + dir[0], j = y + dir[1];
            if (i < 0 || i >= n || j < 0 || j >= m || graph[i][j] == '.') continue;
            dfs(i, j, points);
        }
    }
}
